const colors = require('colors')
const figlet = require('figlet');
const download = require("download-git-repo");
const cp = require('child_process');
const inquirer = require("inquirer");
const { resolve } = require('path');
// const ora = require('ora')
// const ora = require('log')

function hello(){
  console.log(figlet.textSync('dyhao'))
}

module.exports = async function(projectName){
  hello(projectName)
  // const spinner = ora('Loading unicorns').start();
  // console.log(process.cwd())
  console.log('正在创建项目', projectName.brightGreen)
  const p1 = cloneProject('https://gitee.com/daiyuanhao/quick-taro.git', projectName, 'weapp', '小程序')
  const p2 = cloneProject('https://gitee.com/daiyuanhao/quick-egg.git', projectName, 'server', '服务端')
  const p3 = cloneProject('https://gitee.com/linding-tech/quick-web.git', projectName, 'web', '后台')
  await Promise.all([p1, p2, p3])

  inquirer.prompt([
    {
      type: 'confirm',
      message: "打开终端npm i？",
      name: "willnpm",
      default: false
    }
  ]).then(ans => {
    console.log(ans)
    if (ans.willnpm) {
      cp.exec('start cmd /k npm i', { cwd: `${projectName}/${projectName}-weapp`}, ()=>{})
      cp.exec('start cmd /k npm i', { cwd: `${projectName}/${projectName}-server`}, ()=>{})
    }
  })
}

function cloneProject(url, projectName, env, envStr) {
  return new Promise((res, rej) => {
    download(`direct:${url}`, `${projectName}/${projectName}-${env}`, { clone: true }, err => {
      console.log(err ? `${envStr}创建失败` : `${envStr}创建成功`)
      res()
    })
  })
}